package cn.rjzjh.tapestry.tams.services;

import org.apache.commons.lang3.StringUtils;
import org.apache.tapestry5.hibernate.HibernateConfigurer;
import org.hibernate.cfg.Configuration;

import cn.rjzjh.commons.util.apiext.StringUtil;
import cn.rjzjh.commons.util.constant.HibernateConf;

/****
 * 自定义构造HibernateConfigurer
 *
 * @author Administrator
 *
 */
public class HibernateConfigurerEnv implements HibernateConfigurer {
	private final String env_type = "h_type";// hibernate数据库类型
	private final String env_username = "h_username";
	private final String env_pwd = "h_pwd";
	private final String env_ip = "h_ip";
	private final String env_port = "h_port";
	private final String env_databasename = "h_databasename";

	@Override
	public void configure(Configuration configuration) {
		configuration.configure();
		HibernateConf conf = HibernateConf.get(System.getenv(env_type));
		String ip = System.getenv(env_ip).replaceAll("_", ".");
		String port = System.getenv(env_port);
		String databasename = System.getenv(env_databasename);
		if (StringUtils.isNotBlank(ip) && StringUtils.isNotBlank(port)
				&& StringUtils.isNotBlank(databasename)) {
			String url="";
			if(conf==HibernateConf.mysql){
				url = conf.getUrl(ip, Integer.parseInt(port), databasename,
						"characterEncoging", "utf8");
			}else{
				url = conf.getUrl(ip, Integer.parseInt(port), databasename);
			}
			configuration.setProperty("hibernate.connection.url", url);
		}
		configuration.setProperty("hibernate.connection.driver_class",
				conf.getDriverClass());
		configuration.setProperty("hibernate.dialect", conf.getDialect());
		String userName = System.getenv(env_username);
		if (StringUtils.isNotBlank(userName)) {
			configuration
					.setProperty("hibernate.connection.username", userName);
		}
		String pwd = System.getenv(env_pwd);
		if (StringUtils.isNotBlank(pwd)) {
			configuration.setProperty("hibernate.connection.password", pwd);
		}
	}
}
